Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
Mapbox - Cannot trigger marker click with "element".click() after clicking on map

I've currently implemented custom markers on the map using the following code:

// extend mapboxGL class so we can edit the click function
    class CustomMarker extends mapboxgl.Marker {
      // new method onClick, sets _handleClick to a function you pass in
      onClick(handleClick) {
        this._handleClick = handleClick;
        return this;
      }

      // the existing _onMapClick was there to trigger a popup
      // but we are hijacking it to run a function we define
      _onMapClick(e) {
        const targetElement = e.originalEvent.target;
        const element = this._element;

        if (this._handleClick && (targetElement === element || 
        element.contains((targetElement)))) {
          this._handleClick();
        }
      }
    };

    const el1 = document.createElement('div');
    el1.id = "marker1";                                                
    el1.style.marginTop = '-'+(36/2)+'px';
    // make a marker and add it to the map
    new CustomMarker(el1)
    .onClick(() => { //when clicked, define the following function
        console.log(1+1);
        })
        .addTo(map);

I have then added a html button to navigate between markers(i.e next and previous) which then calls something like document.getElementByID("marker1").click() once clicked.

This button works normally and triggers the marker click, however when I click on the mapbox map once (a single click anywhere on the map), document.getElementByID("marker1").click() does not seem to get called when I click the html button. If I drag the map or double click to zoom in after however, the html button starts to work again. Does anyone know why this is happening?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Something very confusing you have made. Actually MapBox Marker does not have click event, but its Element does. So to make things work, you need to use the following:

marker.getElement().addEventListener('click', function(event: PointerEvent) {
  event.stopPropagation(); // to prevent map click event from triggering as well
  ...
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!